export function initPhysics() {
  const state = {
    marbles: [],
    terrain: null,
    hole: {
      position: [0, 0, 0],
      radius: 50,
      strength: 0.5
    },
    obstacles: []
  }

  // 初始化物理参数
  const params = {
    gravity: 9.8,
    friction: {
      grass: 0.3,
      snow: 0.1,
      sand: 0.5,
      town: 0.2,
      wetland: 0.4
    }
  }

  // 滚动音效状态
  const rollingSounds = new Map()

  function update(deltaTime) {
    // 转换为秒
    const dt = deltaTime / 1000

    // 更新每个弹珠状态
    state.marbles.forEach(marble => {
      if (marble.inHole) return

      // 计算地形摩擦力
      const friction = getTerrainFriction(marble.position)

      // 计算洞穴牵引力
      const holeForce = calculateHoleForce(marble)

      // 更新速度
      marble.velocity[0] += holeForce[0] * dt
      marble.velocity[1] += holeForce[1] * dt
      marble.velocity[2] += (-params.gravity) * dt

      // 应用摩擦力
      marble.velocity[0] *= (1 - friction)
      marble.velocity[1] *= (1 - friction)

      // 更新位置
      marble.position[0] += marble.velocity[0] * dt
      marble.position[1] += marble.velocity[1] * dt
      marble.position[2] += marble.velocity[2] * dt

      // 播放滚动音效
      if (window.gameScene?.soundManager) {
        const speed = Math.sqrt(
          marble.velocity[0]**2 + 
          marble.velocity[1]**2 + 
          marble.velocity[2]**2
        )
        
        if (speed > 0.5) {
          if (!rollingSounds.has(marble.id)) {
            window.gameScene.soundManager.play('rolling', 0.3)
            rollingSounds.set(marble.id, true)
          }
        } else {
          rollingSounds.delete(marble.id)
        }
      }

      // 检测碰撞
      checkCollisions(marble)

      // 检测是否进洞
      checkHole(marble)
    })
  }

  function getTerrainFriction(position) {
    // 根据位置获取地形类型对应的摩擦力
    const terrainType = state.terrain.getTypeAt(position[0], position[1])
    return params.friction[terrainType] || 0.3
  }

  function calculateHoleForce(marble) {
    // 计算洞穴对弹珠的牵引力
    const dx = state.hole.position[0] - marble.position[0]
    const dy = state.hole.position[1] - marble.position[1]
    const distance = Math.sqrt(dx*dx + dy*dy)

    // 距离越近牵引力越大
    const force = state.hole.strength / (distance * 0.1 + 1)
    return [
      dx / distance * force,
      dy / distance * force
    ]
  }

  function checkCollisions(marble) {
    // 弹珠间碰撞检测
    state.marbles.forEach(other => {
      if (marble === other || other.inHole) return
      
      // 简单球体碰撞检测
      const dx = other.position[0] - marble.position[0]
      const dy = other.position[1] - marble.position[1]
      const dz = other.position[2] - marble.position[2]
      const distance = Math.sqrt(dx*dx + dy*dy + dz*dz)

      if (distance < marble.radius + other.radius) {
        // 碰撞响应
        handleCollision(marble, other)
      }
    })

    // 地形碰撞检测
    const terrainHeight = state.terrain.getHeightAt(
      marble.position[0], 
      marble.position[1]
    )
    if (marble.position[2] < terrainHeight + marble.radius) {
      marble.position[2] = terrainHeight + marble.radius
      marble.velocity[2] = -marble.velocity[2] * 0.6 // 反弹系数
    }
  }

  function handleCollision(marble1, marble2) {
    // 简单弹性碰撞
    const tempVel = [...marble1.velocity]
    marble1.velocity = [...marble2.velocity]
    marble2.velocity = tempVel
    
    // 播放碰撞音效
    if (window.gameScene?.soundManager) {
      const volume = Math.min(1, Math.sqrt(
        tempVel[0]**2 + 
        tempVel[1]**2 + 
        tempVel[2]**2
      ) / 10)
      window.gameScene.soundManager.play('collision', volume)
    }
  }

  function checkHole(marble) {
    const dx = state.hole.position[0] - marble.position[0]
    const dy = state.hole.position[1] - marble.position[1]
    const distance = Math.sqrt(dx*dx + dy*dy)

    if (distance < state.hole.radius) {
      marble.inHole = true
      // 播放终点音效
      if (window.gameScene?.soundManager) {
        window.gameScene.soundManager.play('goal')
      }
      // 触发得分事件
      onMarbleInHole(marble)
    }
  }

  function onMarbleInHole(marble) {
    // 由游戏逻辑处理得分
  }

  return {
    update,
    setTerrain(terrain) {
      state.terrain = terrain
    },
    setMarbles(marbles) {
      state.marbles = marbles
    },
    setHole(position, radius, strength) {
      state.hole.position = position
      state.hole.radius = radius
      state.hole.strength = strength
    },
    dispose() {
      // 清理资源
    }
  }
}
